/* 
  1.import ether.js
  2.create main function
    2.1 init 2 accounts
    2.2 fund contract with first account
    2.3 check balance of contract
    2.4 fund contract with second account
    2.5 check balance of contract
    2.6 check mapping fundersToAmount
  3.execute main function
*/

const { ethers } = require('hardhat')

async function main() {
	// create factory
	const fundMeFactory = await ethers.getContractFactory('FundMe')
	console.log('contract deploying...')
	// deploy contract from factory,这里的180会被contract FundMe的构造函数construct所接收，作为参数传入到合约中
	const fundMe = await fundMeFactory.deploy(180)
	// 等待合约部署完成
	await fundMe.waitForDeployment()
	console.log('contract deployed to:', fundMe.target)

	// 如果实在sepolia测试网络上，则进行验证合约代码
	if (hre.network.config.chainId == 11155111 && process.env.ETHERSCAN_API_KEY) {
		// 等待五个区块确认
		console.log('waiting for 5 confirmations...')
		await fundMe.deploymentTransaction().wait(5)
		// 这里由于网络问题，经常会失败
		await verifyFundMe(fundMe.target, [180]) // fundMe.target 获取合约地址
		console.log('验证合约成功！')
	} else {
		console.log('verification skipped ')
	}

	// 2.1 init 2 accounts,ethers.getSigners()可以获取到hardhat.config.js文件中配置的accounts
	const [firstAccount, secondAccount] = await ethers.getSigners()
	// 2.2 fund contract with first account
	const fundTx = await fundMe.fund({ value: ethers.parseEther('0.5') })
	await fundTx.wait()
	// 2.3 check balance of contract ,ethers.provider相当于metamask或etherscan
	const balanceOfContract = await ethers.provider.getBalance(fundMe.target)
	console.log(`Balance of contract is: ${balanceOfContract}`)
	// 2.4 fund contract with second account, 不写.connect(account)时，用的是默认账户（hardhat.config.js文件中配置的accounts[0]）
	const fundTxWithSecondAccount = await fundMe
		.connect(secondAccount)
		.fund({ value: ethers.parseEther('0.5') })
	await fundTxWithSecondAccount.wait()
	// 2.5 check balance of contract
	const balanceOfContractAfterSecondFund = await ethers.provider.getBalance(fundMe.target)
	console.log(`Balance of contract is: ${balanceOfContractAfterSecondFund}`)
	// 2.6 check mapping fundersToAmount
	const firstAccountBalanceInFundMe = await fundMe.fundersToAmount(firstAccount.address)
	const secondAccountBalanceInFundMe = await fundMe.fundersToAmount(secondAccount.address)
	console.log(`Balance of first account ${firstAccount.address} is ${firstAccountBalanceInFundMe}`)
	console.log(
		`Balance of second account ${secondAccount.address} is ${secondAccountBalanceInFundMe}`
	)
}

async function verifyFundMe(fundMeAddress, args) {
	await hre.run('verify:verify', {
		address: fundMeAddress,
		constructorArguments: args,
	})
}

main()
	.then()
	.catch((error) => {
		console.error(error)
		// 退出进程，一般0代表正常退出，1代表异常退出
		process.exit(1)
	})
